package org.gulugulubiao.service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gulugulubiao.constant.MessageConstant;
import org.gulugulubiao.constant.PasswordConstant;
import org.gulugulubiao.constant.RoleConstant;
import org.gulugulubiao.constant.StatusConstant;
import org.gulugulubiao.dto.UserLoginDTO;
import org.gulugulubiao.dto.UserPageQueryDTO;
import org.gulugulubiao.entity.User;
import org.gulugulubiao.exception.AccountLockedException;
import org.gulugulubiao.exception.AccountNotFoundException;
import org.gulugulubiao.exception.PasswordEditFailedException;
import org.gulugulubiao.exception.UserNonexistentException;
import org.gulugulubiao.mapper.UserMapper;
import org.gulugulubiao.properties.WechatLoginProperties;
import org.gulugulubiao.result.PageResult;
import org.gulugulubiao.service.UserService;
import org.gulugulubiao.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RequiredArgsConstructor
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private final WechatLoginProperties wechatLoginProperties;
    private final UserMapper userMapper;

    // 微信服务器接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";


//    @Override
//    public String hello() {
//        return userMapper.queryById(1L).toString();
//    }


    /**
     * 调用微信接口服务，获取微信用户的openid
     *
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", wechatLoginProperties.getWechatAppid());
        map.put("secret", wechatLoginProperties.getWechatSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        // 发起请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        if (openid == null) {
            log.error("用code换openId的请求失败，返回默认openid");
            return "123";
        }
        return openid;

    }

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {

        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        // 查询数据库中的数据确认用户是否存在
        User user = userMapper.getByUsername(username);

        // 处理异常情况（1.用户名不存在 2.密码错误 3.账号被锁定）
        if (user == null) {
            // 用户名不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        if (!password.equals(user.getPassword())) {
            // 密码错误
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 登录成功，返回用户信息
        return user;
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    @Override
    public void add(User user) {
        User userTemp = new User();

        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        }

        // 对象拷贝属性
        BeanUtils.copyProperties(user, userTemp);

        // 设置账号的状态，默认正常状态：1为正常状态，0为锁定状态
        userTemp.setStatus(StatusConstant.ENABLE);

        //设置密码，默认密码是PasswordConstant.DEFAULT_PASSWORD

        //设置默认角色，1为管理员，2为用户
        userTemp.setRole(RoleConstant.ROLE_USER);

        // 设置创建时间和更新时间
        userTemp.setCreateTime(LocalDateTime.now());
        userTemp.setUpdateTime(LocalDateTime.now());

        userMapper.insert(userTemp);
    }

    /**
     * 管理员新增用户
     * @param user
     */
    @Override
    public void userInsert(User user) {
        User userTemp = new User();
        //设置密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        }

        //对象拷贝属性
        BeanUtils.copyProperties(user,userTemp);

        //如果没有状态则设定为默认正常状态：1为正常状态，0为锁定状态
        if(userTemp.getStatus() == null){
            userTemp.setStatus(StatusConstant.ENABLE);
        }

        //如果没有设置角色则设定为默认角色用户，1为管理员，2为用户
        if(userTemp.getRole() == null || userTemp.getRole()==0){
            userTemp.setRole(RoleConstant.ROLE_USER);
        }

        // 设置创建时间和更新时间
        userTemp.setCreateTime(LocalDateTime.now());
        userTemp.setUpdateTime(LocalDateTime.now());

        userMapper.insert(userTemp);
    }


    /**
     *  用户分页查询
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResult getUserList(UserPageQueryDTO userPageQueryDTO) {

        // 开始分页查询
        int page = userPageQueryDTO.getPage(); // 从实例中取得当前页
        int pageSize = userPageQueryDTO.getPageSize(); // 从实例中取得每页大小
        PageHelper.startPage(page, pageSize);
        Page<User> userPage = userMapper.getUserList();

        long total = userPage.getTotal();
        List<User> userList = userPage.getResult();

        return new PageResult(total, userList);

    }


    /**
     *  显示id对应的用户信息
     * @param userId
     * @return
     */
    @Override
    public User getUser(Integer userId) {
        // 处理异常情况
        User userTemp = userMapper.getUserById(userId);
        // 该用户不存在
        if(userTemp == null) {
            throw new AccountNotFoundException(MessageConstant.USER_ID_NOT_EXISTS);
        }

        return userTemp;
    }

    /**
     * 编辑用户信息
     * @param user
     */
    @Override
    public void update(User user) {
        User userTemp = new User();
        BeanUtils.copyProperties(user, userTemp);

        userMapper.update(userTemp);

    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Override
    public void userDelete(Integer userId) {
        //查询是否有这个用户
        User userTemp = userMapper.getById(userId);
        if(userTemp==null){
            throw new UserNonexistentException(MessageConstant.USERNONEXISTENT);
        }
        //存在则删除
        userMapper.delete(userId);
    }
}
